package com.lemon.mask.util;

import com.google.common.base.Preconditions;
import com.lemon.mask.annotation.DataMask;
import com.lemon.mask.strategy.DataMaskStrategy;
import com.lemon.mask.strategy.DataMaskStrategyContext;
import com.lemon.mask.strategy.DesensitizedConfig;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lemon
 * @description 敏感字符串遮罩
 * @date 2020-07-01 19:01
 */
@Slf4j
public class DesensitizedUtils {
    private DesensitizedUtils() {
    }

    /**
     * @param dataMask
     * @return com.lemon.mask.strategy.DesensitizedConfig
     * @description
     * @author lemon
     * @date 2020-07-06 11:21
     */
    public static DesensitizedConfig getDesensitizedConfig(DataMask dataMask) {
        DesensitizedConfig desensitizedConfig = new DesensitizedConfig();
        desensitizedConfig.setSensitiveType(dataMask.sensitiveType());
        desensitizedConfig.setPrefixNoMaskSize(dataMask.prefixNoMaskSize());
        desensitizedConfig.setSuffixNoMaskSize(dataMask.suffixNoMaskSize());
        desensitizedConfig.setMaskFlag(dataMask.maskFlag());

        return desensitizedConfig;
    }

    /**
     * @param original
     * @param desensitizedConfig
     * @return java.lang.String
     * @description 对字符串按指定类型脱敏
     * @author lemon
     * @date 2020-07-03 17:52
     */
    public static String maskValue(String original, DesensitizedConfig desensitizedConfig) {
        Preconditions.checkNotNull(desensitizedConfig.getSensitiveType(), "sensitive type should not be null.");

        DataMaskStrategy maskStrategy = DataMaskStrategyContext.getDataMaskStrategy(desensitizedConfig.getSensitiveType());

        if (maskStrategy == null) {
            log.warn("No matching Mask Strategy found for type [{}]", desensitizedConfig.getSensitiveType());
            return original;
        }

        log.debug("Find MaskStrategy [{}]", maskStrategy.getClass());
        return maskStrategy.mask(desensitizedConfig, original);
    }
}